/*
 *	Copyright © 2013 Changsha Shishuo Network Technology Co., Ltd. All rights reserved.
 *	长沙市师说网络科技有限公司 版权所有
 *	http://www.shishuo.com
 */


package com.hlingsoft.kkh.action.v20;

import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.aliyun.openservices.oss.model.PutObjectResult;
import com.hlingsoft.kkh.action.BaseAction;
import com.hlingsoft.kkh.dao.*;
import com.hlingsoft.kkh.entity.*;
import com.hlingsoft.kkh.entity.vo.ImageVo;
import com.hlingsoft.kkh.service.AdminPushService;
import com.hlingsoft.kkh.util.Common;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 评论接口
 *
 * @author Selbylei
 */
@Controller
@RequestMapping("/v20/comment")
public class EventCommentsAction_V20 extends BaseAction {


    @Autowired
    private EventCommentsDao eventCommentsDao;


    @Autowired
    private ImageDao imageDao;

    @Autowired
    private EventsDao eventsDao;

    @Autowired
    private AdminPushService adminPushService;

    @Autowired
    private NotificationDao notificationDao;


    /**
     * 发布评论
     *
     * @param eventsId
     * @param appUserId
     * @param content
     * @param request
     * @return
     */
    @RequestMapping(value = "/add.json", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> add(
            @RequestParam(value = "eventsId") long eventsId,
            @RequestParam(value = "content") String content,
            @RequestParam(value = "appUserId") long appUserId,
            @RequestParam(value = "longitude") Double longitude,
            @RequestParam(value = "latitude") Double latitude,
            @RequestParam(value = "tokeTimes", required = false) String tokeTimes,
            @RequestParam("files") MultipartFile[] files,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            //获取活动
            Events events = eventsDao.getEventsById(eventsId);

            //获取评论人
            AppUser user = userDao.getUserById(appUserId);

            final AppUser eventsUser = userDao.getUserById(events.getAppUserId());

            //添加EventComment
            EventComments eventComments = new EventComments();
            List<Image> imageList = new ArrayList<Image>();

            eventComments.setEventId(eventsId);
            eventComments.setContent(content);
            String images = "";
            List<ImageVo> imageVoList = new ArrayList<ImageVo>();

            if (tokeTimes != null) {
                JSONArray jsonArray = JSONArray.fromObject(tokeTimes);
                long[] tokeTimeArray = (long[]) JSONArray.toArray(jsonArray, long.class);


                for (int i = 0; i < tokeTimeArray.length; i++) {
                    ImageVo imageVo = new ImageVo();
                    imageVo.setFile(files[i]);

                    Date date = Common.transferLongToDate(tokeTimeArray[i] / 1000);   //long类型转成Date类型
                    imageVo.setDate(date);
                    imageVoList.add(imageVo);
                }
            } else {
                for (int i = 0; i < files.length; i++) {
                    ImageVo imageVo = new ImageVo();
                    imageVo.setFile(files[i]);
                    imageVo.setDate(new Date());
                    imageVoList.add(imageVo);
                }
            }

            //设值eventComments中的图片
            for (ImageVo imageVo : imageVoList) {
                String fileName = imageVo.getFile().getOriginalFilename();
                SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = simpleFormat.format(new Date());
                putObject(dateString, fileName, imageVo.getFile().getInputStream(),
                        imageVo.getFile().getSize());
                images += "http://kkh.oss-cn-hangzhou.aliyuncs.com/upload/" + dateString + "/" + fileName + ",";

            }

            if (images.length() > 0) {
                images = images.substring(0, images.length() - 1);
            }
            eventComments.setImage(images);

            //添加跟帖表
            eventComments.setLikeCount(0);
            eventComments.setUnlikeCount(0);
            eventComments.setShareCount(0);
            eventComments.setAppUserId(appUserId);
            eventComments.setCreateTime(new Date());
            eventComments.setUpdateTime(new Date());
            eventComments.setAvailable(1);
            eventComments.setType(0);
            eventCommentsDao.addEventComments(eventComments);

            //添加图片
            for (ImageVo imageVo : imageVoList) {
                Image image = new Image();

                //图片地址
                String fileName = imageVo.getFile().getOriginalFilename();
                SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = simpleFormat.format(new Date());
                putObject(dateString, fileName, imageVo.getFile().getInputStream(),
                        imageVo.getFile().getSize());
                String path = "http://kkh.oss-cn-hangzhou.aliyuncs.com/upload/" + dateString + "/" + fileName;
                image.setPath(path);

                image.setAppUserId(appUserId);
                image.setEventCommentsId(eventComments.getId());
                image.setEventsId(eventsId);
                image.setTagId(0);
                image.setCreateTime(new Date());
                image.setUpdateTime(new Date());
                image.setTokeTime(imageVo.getDate());
                image.setAvailable(1);
                imageDao.addImage(image);
            }


            Date now = new Date();
            Notification notification = new Notification();
            notification.setEventsId(eventsId);
            notification.setMyId(appUserId);
            AppUser myUser = userDao.getUserById(appUserId);
            notification.setMyName(myUser.getName());
            notification.setMyImageHead(myUser.getHeadImage());
            AppUser toUser = userDao.getUserById(events.getAppUserId());
            notification.setToId(toUser.getId());
            notification.setToName(toUser.getName());
            //跟帖的第一张图片
            List<Image> imageList1 = imageDao.getImageByEventCommentsId(eventComments.getId());
            notification.setToImage(imageList1.get(0).getPath());
            notification.setContent("我在你的主题里面跟帖啦");
            notification.setType(3);
            notification.setTarget(2);
            notification.setCreateTime(now);
            notification.setUpdateTime(now);
            notificationDao.addNotification(notification);

            MessageStatus messageStatus = new MessageStatus();
            messageStatus.setAppUserId(events.getAppUserId());
            messageStatus.setType(2);
            messageStatus.setMessageId(notification.getId());
            messageStatusDao.addMessageStatus(messageStatus);


            resultMap.put("images", images);  //返回图片
            resultMap.put("eventComments",eventComments);
            resultMap.put("result", true);

            //消息推送
            String alert = user.getName() + "在你的社区里发了一张图，快去看看";
            adminPushService.pushToClient(alert, new ArrayList<String>() {
                {
                    add(eventsUser.getUdId());
                }
            }, AdminPushService.JOB, false, true);


        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * andriod创建评论
     *
     * @param eventsId
     * @param content
     * @param appUserId
     * @param longitude
     * @param latitude
     * @param tokeTimes
     * @param file1
     * @param file2
     * @param file3
     * @param file4
     * @param request
     * @return
     */
    @RequestMapping(value = "/addC.json", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addC(

            @RequestParam(value = "eventsId") long eventsId,
            @RequestParam(value = "content") String content,

            @RequestParam(value = "appUserId") long appUserId,
            @RequestParam(value = "longitude") Double longitude,
            @RequestParam(value = "latitude") Double latitude,
            @RequestParam(value = "tokeTimes") String tokeTimes,
            @RequestParam(value = "file1", required = false) MultipartFile file1,
            @RequestParam(value = "file2", required = false) MultipartFile file2,
            @RequestParam(value = "file3", required = false) MultipartFile file3,
            @RequestParam(value = "file4", required = false) MultipartFile file4,


            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            //获取活动
            Events events = eventsDao.getEventsById(eventsId);

            //获取评论人
            final AppUser user = userDao.getUserById(appUserId);

            //添加EventComment
            EventComments eventComments = new EventComments();
            List<Image> imageList = new ArrayList<Image>();

            eventComments.setEventId(eventsId);
            eventComments.setContent(content);
            String images = "";

            JSONArray jsonArray = JSONArray.fromObject(tokeTimes);
            long[] tokeTimeArray = (long[]) JSONArray.toArray(jsonArray, long.class);

            List<MultipartFile> filesList = new ArrayList<MultipartFile>();
            if (file1 != null) {
                filesList.add(file1);
            }
            if (file2 != null) {
                filesList.add(file2);
            }
            if (file3 != null) {
                filesList.add(file3);
            }
            if (file4 != null) {
                filesList.add(file4);
            }

            List<ImageVo> imageVoList = new ArrayList<ImageVo>();
            for (int i = 0; i < tokeTimeArray.length; i++) {
                ImageVo imageVo = new ImageVo();
                imageVo.setFile(filesList.get(i));

                Date date = Common.transferLongToDate(tokeTimeArray[i] / 1000);   //long类型转成Date类型
                imageVo.setDate(date);
                imageVoList.add(imageVo);
            }


            //设值eventComments中的图片
            for (ImageVo imageVo : imageVoList) {
                String fileName = imageVo.getFile().getOriginalFilename();
                SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = simpleFormat.format(new Date());
                putObject(dateString, fileName, imageVo.getFile().getInputStream(),
                        imageVo.getFile().getSize());
                images += "http://kkh.oss-cn-hangzhou.aliyuncs.com/upload/" + dateString + "/" + fileName + ",";

            }

            if (images.length() > 0) {
                images = images.substring(0, images.length() - 1);
            }
            eventComments.setImage(images);

            //图片插入图片表
            eventComments.setLikeCount(0);
            eventComments.setUnlikeCount(0);
            eventComments.setShareCount(0);
            eventComments.setAppUserId(appUserId);
            eventComments.setCreateTime(new Date());
            eventComments.setUpdateTime(new Date());
            eventComments.setAvailable(1);
            eventComments.setType(0);
            eventCommentsDao.addEventComments(eventComments);


            //添加图片
            for (ImageVo imageVo : imageVoList) {
                Image image = new Image();

                //图片地址
                String fileName = imageVo.getFile().getOriginalFilename();
                SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = simpleFormat.format(new Date());
                putObject(dateString, fileName, imageVo.getFile().getInputStream(),
                        imageVo.getFile().getSize());
                String path = "http://kkh.oss-cn-hangzhou.aliyuncs.com/upload/" + dateString + "/" + fileName;
                image.setPath(path);

                image.setAppUserId(appUserId);
                image.setEventCommentsId(eventComments.getId());
                image.setEventsId(eventsId);
                image.setTagId(0);
                image.setCreateTime(new Date());
                image.setUpdateTime(new Date());
                image.setTokeTime(imageVo.getDate());
                image.setAvailable(1);
                imageDao.addImage(image);
            }


            Date now = new Date();
            Notification notification = new Notification();
            notification.setEventsId(eventsId);
            notification.setMyId(appUserId);
            AppUser myUser = userDao.getUserById(appUserId);
            notification.setMyName(myUser.getName());
            notification.setMyImageHead(myUser.getHeadImage());
            AppUser toUser = userDao.getUserById(events.getAppUserId());
            notification.setToId(toUser.getId());
            notification.setToName(toUser.getName());
            //跟帖的第一张图片
            List<Image> imageList1 = imageDao.getImageByEventCommentsId(eventComments.getId());
            notification.setToImage(imageList1.get(0).getPath());
            notification.setContent("我在你的主题里面跟帖啦");
            notification.setType(3);
            notification.setTarget(2);
            notification.setCreateTime(now);
            notification.setUpdateTime(now);
            notificationDao.addNotification(notification);

            MessageStatus messageStatus = new MessageStatus();
            messageStatus.setAppUserId(events.getAppUserId());
            messageStatus.setType(2);
            messageStatus.setMessageId(notification.getId());
            messageStatusDao.addMessageStatus(messageStatus);

            resultMap.put("eventComments",eventComments);
            resultMap.put("images", images);  //返回图片
            resultMap.put("result", true);

            //消息推送
            String alert = user.getName() + "在你的社区里发了一张图，快去看看";
            adminPushService.pushToClient(alert, new ArrayList<String>() {
                {
                    add(user.getUdId());
                }
            }, AdminPushService.JOB, false, true);

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 互动评论
     *
     * @param eventCommentsId
     * @param request
     * @return
     */
    @RequestMapping(value = "/interaction.json")
    @ResponseBody
    public Map<String, Object> interaction(
            @RequestParam(value = "appUserId") long appUserId,
            @RequestParam(value = "eventCommentsId") long eventCommentsId,
            @RequestParam(value = "content") String content,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            AppUser user = userDao.getUserById(appUserId);

            EventComments eventComments = eventCommentsDao.getCommentsListById(eventCommentsId);

            final AppUser eventCommentsUser = userDao.getUserById(eventComments.getAppUserId());
            long eventsId = eventComments.getEventId();

            eventComments.setEventId(eventsId);
            eventComments.setContent(content);

            eventComments.setToName(userDao.getUserById(eventComments.getAppUserId()).getName());

            eventComments.setImage("");
            eventComments.setLikeCount(0);
            eventComments.setUnlikeCount(0);
            eventComments.setShareCount(0);
            eventComments.setAppUserId(appUserId);
            eventComments.setCreateTime(new Date());
            eventComments.setUpdateTime(new Date());
            eventComments.setType(0);
            eventCommentsDao.addEventComments(eventComments);


            Date now = new Date();
            Notification notification = new Notification();
            notification.setEventsId(eventsId);
            notification.setMyId(appUserId);
            notification.setMyName(user.getName());
            notification.setMyImageHead(user.getHeadImage());
            AppUser toUser = userDao.getUserById(eventComments.getAppUserId());
            notification.setToId(toUser.getId());
            notification.setToName(toUser.getName());
            List<Image> imageList = imageDao.getImageByEventCommentsId(eventCommentsId);
            notification.setToImage(imageList.get(0).getPath());
            notification.setContent(content);
            notification.setType(3);
            notification.setTarget(2);
            notification.setCreateTime(now);
            notification.setUpdateTime(now);
            notificationDao.addNotification(notification);


            MessageStatus messageStatus = new MessageStatus();
            messageStatus.setAppUserId(eventComments.getAppUserId());
            messageStatus.setType(2);
            messageStatus.setMessageId(notification.getId());
            messageStatusDao.addMessageStatus(messageStatus);


            String alert = user.getName() + "在你创建的社区跟贴了";
            adminPushService.pushToClient(alert, new ArrayList<String>() {
                {
                    add(eventCommentsUser.getUdId());
                }
            }, AdminPushService.JOB, false, true);

            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 回帖详情页
     * @param userId
     * @param eventCommentsId
     * @param request
     * @return
     */
    @RequestMapping(value = "/detail.json")
    @ResponseBody
    public Map<String, Object> detail(
            @RequestParam(value = "userId") long userId,
            @RequestParam(value = "eventCommentsId") long eventCommentsId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            EventComments eventComments = eventCommentsDao.getCommentsListById(eventCommentsId);

            List<Image> imageList = imageDao.getImageByEventCommentsId(eventCommentsId);
            List<AppUser> likeUserList = new ArrayList<AppUser>();
            eventComments.setImageList(imageList);
            if (likesDao.getCIsLikes(userId, eventCommentsId).size() != 0) {
                eventComments.setIslike(1);
            } else {
                eventComments.setIslike(0);
            }
            List<Likes> likesList = likesDao.getLikesByEventCommentsId(eventCommentsId, 0, 10);
            for (Likes likes : likesList) {
                AppUser user = userDao.getUserById(likes.getMyId());
                if (user!=null){
                    likeUserList.add(user);
                }
            }
            eventComments.setLikeUserList(likeUserList);
            eventComments.setLikeCount(likesDao.getLikesByEventCommentsIdCount(eventCommentsId));
            eventComments.setReplyList(replyDao.getAllReplyByEventCommentsId(eventCommentsId));
            eventComments.setUserName(userDao.getUserById(eventComments.getAppUserId()).getName());
            eventComments.setHeadImage(userDao.getUserById(eventComments.getAppUserId()).getHeadImage());

            resultMap.put("eventComments",eventComments);
            resultMap.put("result",true);

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    public void putObject(String date, String filename, InputStream content,
                          Long size) throws FileNotFoundException {

        // 初始化OSSClient


        OSSClient client = new OSSClient("W6PVM427mSEWlvEz",
                "h7NoXlxcjCqyeOWeuT43LungGmGRSd");

        // 获取指定文件的输入流
        // File file = new File(filePath);
        // InputStream content = new FileInputStream(file);

        // 创建上传Object的Metadata
        ObjectMetadata meta = new ObjectMetadata();

        // 必须设置ContentLength
        meta.setContentLength(size);

        // 上传Object.
        PutObjectResult result = client.putObject("kkh", "upload/" + date
                + "/" + filename, content, meta);

        // 打印ETag
        System.out.println(result.getETag());
    }
}
